#include "graphs.h"
#include "ui_graphs.h"

Graphs::Graphs(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Graphs)
{
    ui->setupUi(this);
    this->setWindowTitle("曲线图");this->setAttribute(Qt::WA_Hover, true);
    UiConstr();
    AddWidget = CreateWidget("添加");
    DelWidget = CreateWidget("删除");
    UpdateTimer = new QTimer();
    UpdateTimer->setInterval(1000);
    SingalsToSlots();
}

Graphs::~Graphs()
{
    delete ui;
}

void Graphs::GiveMeList(QVector<GraphsData *> list)
{
    TotalGraphsList = list;
    for(GraphsData * t : list)
    {
        AddWidget->addItem(t->Name);
    }
}

int Graphs::FindGrapFromName(QString Name, QVector<GraphsData*> list)
{
    for(int i = 0; i < list.size(); i++)
    {
        if(list[i]->Name == Name) return i;
    }
    return -1;
}

void Graphs::NewLine(QString name)
{
    int graphCount = ui->customPlot->graphCount();
    // 生成0-359之间的随机色相值
    int hue = QRandomGenerator::global()->bounded(360);
    // 固定高饱和度（转换为0-255范围，对应70%-100%）
    int saturation = QRandomGenerator::global()->bounded(180, 256);
    // 固定中等明度（转换为0-255范围，对应50%-80%）
    int value = QRandomGenerator::global()->bounded(200, 255);
    QPen axisPen;
    axisPen.setWidth(2);
    axisPen.setColor(QColor::fromHsv(hue, saturation, value));
    ui->customPlot->addGraph();
    ui->customPlot->graph(graphCount)->setName(name);
    ui->customPlot->graph(graphCount)->setPen(axisPen);
    //画布更新
    ui->customPlot->replot();
}

void Graphs::UiConstr()
{
    ui->customPlot->setBackground(QColor(59,59,59));
    QFont xFont = ui->customPlot->xAxis->labelFont();
    xFont.setPixelSize(15);
    //x
    ui->customPlot->xAxis->setTickLabelColor(Qt::white);
    ui->customPlot->xAxis->setLabelColor(QColor(50, 190, 90));
    ui->customPlot->xAxis->setBasePen(QPen(QColor(50, 190, 90)));
    ui->customPlot->xAxis->setTickPen(QPen(QColor(51, 136, 255)));
    ui->customPlot->xAxis->setSubTickPen(QColor(51, 255, 255));
    //y
    ui->customPlot->yAxis->setTickLabelColor(Qt::white);
    ui->customPlot->yAxis->setLabelColor(QColor(50, 190, 90));
    ui->customPlot->yAxis->setBasePen(QPen(QColor(50, 190, 90)));
    ui->customPlot->yAxis->setTickPen(QPen(QColor(51, 136, 255)));
    ui->customPlot->yAxis->setSubTickPen(QColor(51, 255, 255));

    ui->customPlot->xAxis->setLabelFont(xFont);
    ui->customPlot->yAxis->setLabelFont(xFont);

    //设置可拖动选择
    ui->customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom| QCP::iSelectPlottables);
    //横纵坐标标签
    ui->customPlot->xAxis->setLabel("时间");
    ui->customPlot->yAxis->setLabel("数据");
    //使用半透明图列
    ui->customPlot->legend->setVisible(true);
    ui->customPlot->legend->setBrush(QColor(150, 150, 150, 160));
    ui->customPlot->legend->setTextColor(QColor(255, 255, 255));
    ui->customPlot->axisRect()->insetLayout()->setInsetAlignment(0, Qt::AlignBottom |Qt::AlignLeft);//设置位置

    //横坐标显示时间
    QSharedPointer<QCPAxisTickerTime> timeTicker(new QCPAxisTickerTime);
    timeTicker->setTimeFormat("%h:%m:%s");

    ui->customPlot->xAxis->setTicker(timeTicker);

    // 声明时间获取变量，实际情况中，获取的是当前时间的总秒数
    double hour = QTime::currentTime().hour()*60*60;
    double minute = QTime::currentTime().minute()*60;
    double second = QTime::currentTime().second();

    double nowtime = hour + minute + second;

    // x轴刻度
    ui->customPlot->xAxis->ticker()->setTickCount(8);//8个主刻度
    ui->customPlot->yAxis->ticker()->setTickCount(10);//8个主刻度
    ui->customPlot->xAxis->ticker()->setTickStepStrategy(QCPAxisTicker::tssReadability);//可读性优于设置

    ui->customPlot->xAxis->setRange(nowtime - 180,nowtime);
}

void Graphs::SingalsToSlots()
{
    //添加窗口
    connect(AddWidget, &QListWidget::itemDoubleClicked, this,[=](QListWidgetItem *item)
    {
        int i1 = FindGrapFromName(item->text(), AddedGraphsList);        //判断画布中是否存在该对象
        int i2 = FindGrapFromName(item->text(), TotalGraphsList);    //从
        if(i1 != -1) return;
//qDebug() << TotalGraphsList[i2]->Name << *TotalGraphsList[i2]->value;
        AddedGraphsList.append(new GraphsData);          //新建画布使用的对象
        AddedGraphsList.last()->Name = TotalGraphsList[i2]->Name;
        AddedGraphsList.last()->value = TotalGraphsList[i2]->value;
        AddedGraphsList.last()->MultipNum = TotalGraphsList[i2]->MultipNum;
        DelWidget->addItem(AddedGraphsList.last()->Name);
        NewLine(item->text());

        if(!UpdateTimer->isActive())
        {
            ui->btnStart->setEnabled(true);
            Started = true;
            UpdateTimer->start();
            ui->btnStart->setText("暂停");
        }
    });
    //删除窗口
    connect(DelWidget, &QListWidget::itemDoubleClicked, this,[=](QListWidgetItem *item)
    {
        int index = FindGrapFromName(item->text(),AddedGraphsList);     //通过双击的项目名获取该名在数据列表的位置
        AddedGraphsList.removeAt(index);
        ui->customPlot->removeGraph(index);
        item->setHidden(true);
        DelWidget->removeItemWidget(item);
        ui->customPlot->replot();
        if(AddedGraphsList.isEmpty())
        {
            ui->btnStart->setEnabled(false);
            UpdateTimer->stop();
            ui->btnStart->setText("开始");
            Started = false;
        }
    });
    connect(this,&QObject::destroyed,this,[=]{AddWidget->close();DelWidget->close();});
    connect(UpdateTimer, &QTimer::timeout, this, &Graphs::on_Update);
}

void Graphs::on_Update()
{
    //更新横坐标
    double hour = QTime::currentTime().hour()*60*60;
    double minute = QTime::currentTime().minute()*60;
    double second = QTime::currentTime().second();
    double nowtime = hour + minute + second;

    //时间轴每秒更新显示前3分钟到当前时间范围
    ui->customPlot->xAxis->setRange(nowtime - 180,nowtime);
    //数据轴根据值大小自动调整
    ui->customPlot->yAxis->m_rescale();
    for(int i = 0; i < AddedGraphsList.size(); i++)
        ui->customPlot->graph(i)->addData(nowtime,(float)*AddedGraphsList.at(i)->value * (*AddedGraphsList.at(i)->MultipNum));
    //画布更新
    ui->customPlot->replot();
}

void Graphs::on_btnStart_clicked()
{
    if(AddedGraphsList.isEmpty()) return;
    if(Started)
    {
        Started = false;
        UpdateTimer->stop();
        ui->btnStart->setText("开始");
    }else
    {
        Started = true;
        UpdateTimer->start();
        ui->btnStart->setText("暂停");
    }
}

void Graphs::on_btnAdd_clicked()
{
    AddWidget->show();
}

void Graphs::on_btndel_clicked()
{
    DelWidget->show();
}

QListWidget *Graphs::CreateWidget(QString title)
{
    QListWidget *widget = new QListWidget(this);
    widget->setWindowTitle(title);
//    widget->setAlternatingRowColors(true);
    QFont font = widget->font();
    font.setPointSize(font.pointSize() + 2);
    widget->setFont(font);
    QString listStyle = R"(
           /* 主列表样式 */
           QListWidget {
               font-family: "Segoe UI", "Microsoft YaHei";
               color: #FFFFFF;
           }

           /* 列表项基础样式 */
           QListWidget::item {
               background: transparent;
               border: none;
               padding: 8px 12px;
               margin: 2px 0;
               border-radius: 6px;
           }

           /* 交互状态 */
           QListWidget::item:hover {
               background: #F5F5F5;
                color: #333333;
           }
           QListWidget::item:selected {

               background: #E3F2FD;
               color: #333333;
           }
           QListWidget::item:selected:!active {
               background: #EEEEEE;
           }
       )";
    widget->setFocusPolicy(Qt::NoFocus);        //去掉焦点框，虚线框很丑。。
    widget->setStyleSheet(listStyle);
    widget->setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint);
    widget->resize(480,400);
    return widget;
}
